package com.itphy.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.annotation.Resource;

@Configuration
public class myConfig extends WebSecurityConfigurerAdapter
{
    @Resource
    private MyUserDetailsService myUserDetailsService;
    @Resource
    private TokenAuthenticationProvider tokenAuthenticationProvider;



    public TokenAuthenticationFilter tokenAuthenticationFilter() throws Exception {
        TokenAuthenticationFilter tokenAuthenticationFilter = new TokenAuthenticationFilter();
        tokenAuthenticationFilter.setAuthenticationManager(authenticationManager());
        return tokenAuthenticationFilter;
    }


    @Override   //授权
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("授权2");

        http
//                .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/al").hasAuthority("vip1")
                .anyRequest().permitAll();

        http.formLogin()//自动跳转login页面
                .usernameParameter("username")//设置模板用户name
                .passwordParameter("password")//设置模板密码name
                .loginPage("/toLogin")//设置登录页面
                .loginProcessingUrl("/login")
                .and()
                .csrf()
                .disable();

    }

    @Override //认证
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("认证1");
        auth
            .authenticationProvider(tokenAuthenticationProvider)
            .userDetailsService(myUserDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());
    }

}
